package com.yzsj.socket.business.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.yzsj.socket.business.domain.ElectricEnergyPO;
import com.yzsj.socket.business.domain.vo.CategoryVO;
import com.yzsj.socket.business.domain.vo.ClassificationVO;
import com.yzsj.socket.business.service.CategoryService;
import com.yzsj.socket.business.service.ClassificationService;
import com.yzsj.socket.business.service.ElectricEnergyService;
import com.yzsj.socket.business.service.TempSituationService;
import com.yzsj.socket.util.DateMyUtils;
import com.yzsj.socket.util.Global;
import com.yzsj.socket.util.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/index")
public class IndexController {

    @Autowired
    private TempSituationService indexService;

    @Autowired
    private ElectricEnergyService energyService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ClassificationService classificationService;

    @Value("${ucweb.url}")
    private String ucwebUrl;

    /**
     * @author zhangxuan
     * @date 2019-08-12
     * 电能使用TOP10
     */
    @ResponseBody
    @RequestMapping(value = "/findTopTen")
    public ResponseBean findTopTen() {
        List<ElectricEnergyPO> list = energyService.findTopTen();
        return ResponseBean.success(list);
    }

    /**
     * @author zhangxuan
     * @date 2019-08-12
     * 温度情况
     */
    @ResponseBody
    @RequestMapping(value = "/tempSituation")
    public ResponseBean tempSituation() {
        Map<Integer, Integer> map = Maps.newHashMap();
        List<Object> tempList = indexService.getTempSituation();
        if (tempList != null && tempList.size() > 0) {
            for (int i = 0; i < tempList.size(); i++) {
                Map<Integer, Integer> mapObj = (Map<Integer, Integer>) tempList.get(i);
                map.put(mapObj.get("tempLevel"), mapObj.get("num"));
            }
        }
        return ResponseBean.success(map);
    }

    /**
     * @author zhangxuan
     * @date 2019-08-12
     * 服务器性能
     */
    @ResponseBody
    @RequestMapping(value = "/systemSituation")
    public ResponseBean systemSituation() {
        Map<String, String> map = Maps.newHashMap();
        String disk = Global.getDisk();//硬盘
        String memery = Global.getMemery();//内存
        String cpu = Global.getCpuRatioForWindows();//cpu
        map.put("disk", disk);
        map.put("memery", memery);
        map.put("cpu", cpu);
        return ResponseBean.success(map);
    }

    /**
     * @author zhangxuan
     * @date 2019-08-12
     * 报警情况
     */
    @ResponseBody
    @RequestMapping(value = "/alarmSituation")
    public ResponseBean getAlarmSituation() {
        List<Object> list;
        list = Global.getAlarm();
        return ResponseBean.success(list);
    }

    /**
     * @author wjl
     * @date 2019-08-13
     * 报警统计
     */
    @ResponseBody
    @RequestMapping(value = "/alarmStatistics")
    public ResponseBean getAlarmStatistics() {
        Map<Integer, Map<String, Integer>> statisticsOfMonth = new HashMap<>();
        try {
            String result = "";
            String tmpUrl = ucwebUrl + "alarm/histdb/list?time=" + DateMyUtils.getYearStartTime(System.currentTimeMillis(), "GMT+8:00")+"&count=999999";
            URL url = new URL(tmpUrl);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            connection.connect();
            InputStream is = connection.getInputStream();
            InputStreamReader ir = new InputStreamReader(is, "UTF-8");
            BufferedReader in = new BufferedReader(ir);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            in.close();
            if (result != "" && !result.equals("[]")) {
                JSONArray jsonArray = JSONArray.parseArray(result);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject o = (JSONObject) jsonArray.get(i);
                    //报警类型 1严重  2一般  3轻微
                    String almPriority = (String) o.get("AlmPriority");
                    String almTime = (String) o.get("AlmTime");
                    //获取告警月份
                    int month = DateMyUtils.getMonth(almTime);
                    Map<String, Integer> degreeToCount = statisticsOfMonth.get(month);
                    if (degreeToCount == null) {
                        degreeToCount = new HashMap<>(16);
                        degreeToCount.put(almPriority, 1);
                        statisticsOfMonth.put(month, degreeToCount);
                    } else {
                        Integer count = degreeToCount.get(almPriority);
                        if (count == null) {
                            degreeToCount.put(almPriority, 1);
                        } else {
                            count = count + 1;
                            degreeToCount.put(almPriority, count);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseBean.success(statisticsOfMonth);
    }


    /**
     * @author wjl
     * @date 2019-08-13
     * 报警占比分析
     */
    @ResponseBody
    @RequestMapping(value = "/alarmRatioAnalysis")
    public ResponseBean getAlarmRatioAnalysis() {
        Map<String, String> percent = new HashMap<>(16);
        DecimalFormat df = new DecimalFormat("#.00");
        Map<String, String> notAlarmMap = new HashMap<>(16);
        Map<String, String> alarmMap = new HashMap<>(16);
        List<CategoryVO> notAlarmCount = categoryService.getNotAlarmCount();
        if (notAlarmCount != null && notAlarmCount.size() > 0) {
            for (CategoryVO vo : notAlarmCount) {
                notAlarmMap.put(vo.getName(), String.valueOf(vo.getCount()));
            }
        }
        List<CategoryVO> alarmCount = categoryService.getAlarmCount();
        if (alarmCount != null && alarmCount.size() > 0) {
            for (CategoryVO vo : alarmCount) {
                alarmMap.put(vo.getName(), String.valueOf(vo.getCount()));
            }
        }
        if (alarmMap.size() > 0) {
            for (CategoryVO vo : alarmCount) {
                String name = vo.getName();
                Double alarmC = Double.valueOf(alarmMap.get(name));
                Double totalC = Double.valueOf(notAlarmMap.get(name));
                percent.put(name, df.format(alarmC / totalC * 100) + "%");
            }
        }
        return ResponseBean.success(percent);
    }

    /**
     * @author wjl
     * @date 2019-08-13
     * 设备情况
     */
    @ResponseBody
    @RequestMapping(value = "/equipmentSituation")
    public ResponseBean getEquipmentSituation() {
        List<ClassificationVO> lists = classificationService.getEquipmentSituation();
        for (ClassificationVO vo : lists) {
            if ("电量仪".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(67);
                vo.setKpiTotal(469);
            } else if ("列头柜".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(6);
                vo.setKpiTotal(42);
            } else if ("UPS".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(3);
                vo.setKpiTotal(60);
            } else if ("温湿度".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(17);
                vo.setKpiTotal(51);
            } else if ("漏水".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(4);
                vo.setKpiTotal(12);
            } else if ("空调".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(7);
                vo.setKpiTotal(133);
            } else if ("恒湿机".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(3);
                vo.setKpiTotal(12);
            } else if ("冷水机".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(2);
                vo.setKpiTotal(12);
            } else if ("新风".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(1);
                vo.setKpiTotal(2);
            } else if ("门禁".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(19);
                vo.setKpiTotal(1);
            } else if ("视频".equalsIgnoreCase(vo.getAcName())) {
                vo.setEquipmentTotal(28);
                vo.setKpiTotal(0);
            }
        }
        return ResponseBean.success(lists);
    }

}
